package com.example.pages;


import com.example.SortedListOf;
import com.example.User;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import java.util.ArrayList;
import java.util.List;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

public class UserManagementPage extends InternalPage {

    @FindBy(id = "username")
    public WebElement usernameField;

    @FindBy(name = "email")
    public WebElement emailField;

    @FindBy(id = "password")
    public WebElement passwordField;

    @FindBy(id = "password2")
    public WebElement passwordConfirmationField;

    @FindBy(name = "submit")
    public WebElement saveButton;

    @FindBy(xpath = "//a[contains(text(),'ndv') and contains(@href, './?go=user')]")
    public WebElement userNDVLink;

    @FindBy(css = "h2")
    public WebElement title;

    @FindBy(xpath = "//div[@id='content']/section/div[2]/table/tbody/tr")
    public List<WebElement> usersRows;

    public User deletedUser = null;

    private boolean isNewUserAdded() {
        return userNDVLink.isDisplayed();
    }

    public UserPage goToEditUserPage() {
        userNDVLink.click();
        return MyPageFactory.getPage(driver, UserPage.class);
    }

    public UserManagementPage createUser(User user) {
        usernameField.clear();
        usernameField.sendKeys(user.name);
        emailField.clear();
        emailField.sendKeys(user.email);
        passwordField.clear();
        passwordField.sendKeys(user.password);
        passwordConfirmationField.clear();
        passwordConfirmationField.sendKeys(user.password);
        saveButton.click();
        return MyPageFactory.getPage(driver, UserManagementPage.class);
    }

    public UserManagementPage deleteFirstUser() {
        for (WebElement row : usersRows) {
            if (!convertRowToUser(row).role.equals("Admin")) {
                deletedUser = convertRowToUser(row);
                row.findElement(By.xpath("./td[6]/a")).click();
                wait_().until(alertIsPresent()).accept();
                break;
            }

        }

        return MyPageFactory.getPage(driver, UserManagementPage.class);
    }

    public SortedListOf<User> getUsers() {
        List<User> users = new ArrayList<User>();

        for (WebElement row : usersRows){
            users.add(convertRowToUser(row));
        }
        return new SortedListOf<User>(users);
    }

    private User convertRowToUser(WebElement row) {
        List<WebElement> cells = row.findElements(By.tagName("td"));
        return new User()
                .withName(cells.get(1).getText())
                .withEmail(cells.get(2).getText())
                .withRole(cells.get(3).getText());
    }



}
